<template>
  <div class="club-list-container">
    <el-card class="club-list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="title">社团列表</h2>
          </div>
          <div class="header-right">
            <div class="search-filter">
              <el-select v-model="status" placeholder="选择状态" clearable @change="handleSearch" class="status-select">
                <el-option label="审核中" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
              <el-input
                v-model="searchQuery"
                placeholder="搜索社团名称"
                class="search-input"
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button 
                type="primary" 
                class="back-button"
                @click="goBack"
                :icon="ArrowLeft"
              >
                返回首页
              </el-button>
            </div>
          </div>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loading">
        <el-col :span="8" v-for="club in displayedClubs" :key="club.id" class="club-card-col">
          <el-card class="club-card" :body-style="{ padding: '0px' }">
            <img 
              :src="club.coverUrl || defaultCover" 
              class="club-image" 
              @error="handleImageError"
            />
            <div class="club-info">
              <h3>{{ club.name }}</h3>
              <p class="description">{{ club.description }}</p>
              <div class="club-footer">
                <el-tag :type="getStatusType(club.status)">{{ club.status }}</el-tag>
                <div class="button-group">
                  <el-button type="primary" size="small" @click="viewClubDetail(club)">
                    查看详情
                  </el-button>
                  <el-button 
                    type="success" 
                    size="small" 
                    @click="joinClub(club.id)"
                    :disabled="club.status !== '已通过'"
                  >
                    加入社团
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div class="pagination-container">
        <el-pagination
          v-model="currentPage"
          :page-size="pageSize"
          :total="totalClubs"
          :page-sizes="[9, 18, 27, 36]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 悬浮创建社团按钮 -->
    <div class="fab-create-club" @click="goToCreateClub">
      <span class="plus-icon">+</span>
    </div>
    <!-- 创建社团对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建社团"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="100px"
      >
        <el-form-item label="社团名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入社团名称"></el-input>
        </el-form-item>
        <el-form-item label="社团描述" prop="description">
          <el-input
            type="textarea"
            v-model="createForm.description"
            :rows="3"
            placeholder="请输入社团描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图片" prop="file">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept="image/*"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateForm" :loading="submitLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 社团详情弹框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="社团详情"
      width="80%"
      :close-on-click-modal="false"
      class="club-detail-dialog"
    >
      <div class="club-detail-content" v-loading="detailLoading">
        <!-- 顶部信息 -->
        <div class="club-header">
          <div class="club-cover">
            <img :src="currentClub.coverUrl || defaultCover" @error="handleImageError" alt="社团封面" />
          </div>
          <div class="club-basic-info">
            <h1 class="club-name">{{ currentClub.name }}</h1>
            <div class="club-status">
              <el-tag :type="getStatusType(currentClub.status)">{{ currentClub.status }}</el-tag>
              <el-tag :type="getActivityStatusType(currentClub.activityStatus)" class="ml-2">
                {{ currentClub.activityStatus }}
              </el-tag>
            </div>
            <p class="club-description">{{ currentClub.description }}</p>
            <div class="club-stats">
              <!-- <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>成员数：{{ currentClub.memberCount || 0 }}</span>
              </div> -->
              <div class="stat-item">
                <el-icon><Calendar /></el-icon>
                <span>创建时间：{{ formatDate(currentClub.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <el-tabs v-model="activeTab" class="club-tabs">
          <!-- 社团详情 -->
          <el-tab-pane label="社团详情" name="details">
            <div class="club-details">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="社团类别">{{ currentClub.category || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="最大成员数">{{ currentClub.maxMembers || '不限' }}</el-descriptions-item>
                <el-descriptions-item label="例会时间">{{ currentClub.meetingTime || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="例会地点">{{ currentClub.meetingLocation || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ currentClub.contactPerson || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ currentClub.contactPhone || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="联系邮箱">{{ currentClub.contactEmail || '未设置' }}</el-descriptions-item>
              </el-descriptions>
              
              <div class="section-title">社团成就</div>
              <div class="achievements">{{ currentClub.achievements || '暂无成就' }}</div>
              
              <div class="section-title">社团规章制度</div>
              <div class="rules">{{ currentClub.rules || '暂无规章制度' }}</div>
            </div>
          </el-tab-pane>

          <!-- 成员列表 -->
          <el-tab-pane label="成员列表" name="members">
            <div class="members-section">
              <el-table :data="currentClub.members || []" style="width: 100%">
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="joinTime" label="加入时间" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getMemberStatusType(scope.row.status)">
                      {{ getMemberStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 活动列表 -->
          <el-tab-pane label="活动列表" name="activities">
            <div class="activities-section">
              <el-table :data="currentClub.activities || []" style="width: 100%">
                <el-table-column prop="title" label="活动标题" />
                <el-table-column prop="startTime" label="开始时间" />
                <el-table-column prop="endTime" label="结束时间" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getActivityStatusTypeForList(scope.row.status)">
                      {{ getActivityStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { Search, ArrowLeft, Plus, User, Calendar } from '@element-plus/icons-vue'
import { clubApi } from '../api'
import { ElMessage } from 'element-plus'
import defaultCover from '../assets/default-club-cover.jpg'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const clubs = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(9)
const totalClubs = ref(0)
const status=ref('')

// 社团详情相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const activeTab = ref('details')
const currentClub = ref({})

// 获取社团列表
const getClubList = async () => {
  loading.value = true
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (!userInfo || !userInfo.id) {
      ElMessage.error('获取用户信息失败，无法加载社团列表')
      clubs.value = []
      totalClubs.value = 0
      loading.value = false
      return
    }

    const response = await clubApi.getClubList({
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        name: searchQuery.value,
        status: status.value
    }, userInfo.id)

    if (response.code === 200) {
      clubs.value = response.data.data.map(club => ({
        ...club,
        status: getStatusText(club.status),
      }))
      totalClubs.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
    ElMessage.error('获取社团列表失败')
  } finally {
    loading.value = false
  }
}

// 状态码转换为文本
const getStatusText = (status) => {
  const statusMap = {
    0: '审核中',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '审核中': 'warning',
    '已通过': 'success',
    '已拒绝': 'danger',
    '未知状态': 'info'
  }
  return statusMap[status] || 'info'
}

// 计算属性：显示的社团列表
const displayedClubs = computed(() => {
  return clubs.value
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getClubList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getClubList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getClubList()
}

// 查看社团详情
const viewClubDetail = async (club) => {
  detailLoading.value = true
  try {
    // 获取社团基本详情
    const detailResponse = await clubApi.getClubDetail(club.id)
    let clubDetails = {}
    if (detailResponse.code === 200) {
      clubDetails = detailResponse.data || {}
    } else {
      ElMessage.error(detailResponse.message || '获取社团详情失败')
      detailLoading.value = false
      return
    }

    // 获取社团成员和活动原始数据
    const membersActivitiesResponse = await clubApi.getClubMembersAndActivities(club.id)
    let processedMembers = []
    let processedActivities = []

    if (membersActivitiesResponse.code === 200 && membersActivitiesResponse.data) {
      const rawData = membersActivitiesResponse.data;
      const memberUsernames = new Set();
      const activityKeys = new Set(); // 使用 title + startTime + endTime 作为活动的唯一键

      rawData.forEach(item => {
        // 提取成员信息并去重
        if (item.username && !memberUsernames.has(item.username)) {
          processedMembers.push({
            username: item.username,
            joinTime: formatDate(item.joinTime), // 格式化加入时间
            status: item.status
          });
          memberUsernames.add(item.username);
        }

        // 提取活动信息并去重
        const activityKey = `${item.activityTitle}-${item.startTime}-${item.endTime}`;
        if (item.activityTitle && !activityKeys.has(activityKey)) {
          processedActivities.push({
            title: item.activityTitle,
            startTime: formatDate(item.startTime), // 格式化开始时间
            endTime: formatDate(item.endTime),     // 格式化结束时间
            status: item.activityStatus
          });
          activityKeys.add(activityKey);
        }
      });
    } else {
      ElMessage.warning(membersActivitiesResponse.message || '获取社团成员和活动失败');
      // 即使成员活动获取失败，也继续展示基本详情
    }

    // 合并数据
    currentClub.value = {
      ...club,
      ...clubDetails,
      members: processedMembers, // 使用处理后的成员列表
      activities: processedActivities, // 使用处理后的活动列表
      // 如果后端返回的数据结构与前端展示需要的不完全一致，可以在这里做数据转换
      memberCount: clubDetails.memberCount || (processedMembers ? processedMembers.length : 0), // 如果详情接口没有成员数，使用获取到的成员列表长度
      activityStatus: clubDetails.activityStatus || '正常'
    }
    
    detailDialogVisible.value = true

  } catch (error) {
    console.error('获取社团详情或成员活动失败:', error)
    ElMessage.error('获取社团详情或成员活动失败')
  } finally {
    detailLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getClubList()
})

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = defaultCover
}

// 在 script setup 部分添加
// 加入社团
const joinClub = async (clubId) => {
  try {
    // 从localStorage获取用户信息并解析
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (!userInfo || !userInfo.username || !userInfo.id) {
      ElMessage.warning('请先登录或用户信息不完整')
      return
    }
    
    const response = await clubApi.joinClub(clubId, userInfo.username)
    if (response.code === 200) {
      ElMessage.success(response.message || '申请加入社团成功')
      getClubList() // 刷新列表，会自动带上userId
    } else {
      ElMessage.error(response.message || '申请加入社团失败')
    }
  } catch (error) {
    console.error('申请加入社团失败:', error)
    ElMessage.error('申请加入社团失败')
  }
}
// 返回首页
const goBack = () => {
  router.push('/home')
}

// 创建社团相关的响应式数据
const createDialogVisible = ref(false)
const createFormRef = ref(null)
const imageUrl = ref('')
const submitLoading = ref(false)
const selectedFile = ref(null)
const createForm = reactive({
  name: '',
  description: ''
})
const createRules = {
  name: [
    { required: true, message: '请输入社团名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入社团描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}
// 处理文件选择
const handleFileChange = (file) => {
  selectedFile.value = file.raw
  imageUrl.value = URL.createObjectURL(file.raw)
}
// 提交创建社团表单
const submitCreateForm = async () => {
  if (!createFormRef.value) return
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!selectedFile.value) {
        ElMessage.warning('请选择社团封面图片')
        return
      }
      submitLoading.value = true
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        if (!userInfo || !userInfo.id) {
          ElMessage.warning('请先登录或用户信息不完整')
          submitLoading.value = false
          return
        }
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        formData.append('clubs', new Blob([JSON.stringify(createForm)], {
          type: 'application/json'
        }))
        formData.append('user_id', userInfo.id)
        const response = await clubApi.createClub(formData)
        if (response.code === 200) {
          ElMessage.success('创建社团申请提交成功'||response.message)
          createDialogVisible.value = false
          resetCreateForm()
          getClubList() // 刷新列表
        } else {
          ElMessage.error(response.message || '创建社团失败')
        }
      } catch (error) {
        console.error('创建社团失败:', error)
        ElMessage.error('创建社团失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}
// 重置创建表单
const resetCreateForm = () => {
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
  imageUrl.value = ''
  selectedFile.value = null
  createForm.name = ''
  createForm.description = ''
}
// 修改原有的跳转函数为打开对话框
const goToCreateClub = () => {
  createDialogVisible.value = true
}

// 状态相关方法
const getActivityStatusType = (status) => {
  const statusMap = {
    '正常': 'success',
    '暂停活动': 'warning',
    '已解散': 'danger'
  }
  return statusMap[status] || 'info'
}

const getMemberStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

const getMemberStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '正常',
    2: '已退出'
  }
  return statusMap[status] || '未知状态'
}

const getActivityStatusTypeForList = (status) => {
  const statusMap = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'warning',
    4: 'info'
  }
  return statusMap[status] || 'info'
}

const getActivityStatusText = (status) => {
  const statusMap = {
    0: '未发布',
    1: '已发布',
    2: '已取消',
    3: '已延期',
    4: '已结束'
  }
  return statusMap[status] || '未知状态'
}

// 工具方法
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}
</script>

<style scoped>
.club-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
  padding: 32px 0 40px 0;
}

.club-list-card {
  max-width: 1200px;
  margin: 0 auto 32px auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  border: 1.5px solid #e3e8ee;
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 0 0 0;
}

.header-left {
  flex: 1;
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 2;
}

.search-filter {
  display: flex;
  gap: 14px;
  align-items: center;
  justify-content: flex-end;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #22577a;
  margin: 0;
  letter-spacing: 1.5px;
}

.back-button {
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  border-radius: 8px;
  background: linear-gradient(90deg, #bfc6d1 0%, #e0e4ea 100%);
  border: none;
  color: #555;
}
.back-button:hover {
  transform: translateX(-5px);
  background: linear-gradient(90deg, #e0e4ea 0%, #bfc6d1 100%);
  color: #333;
}

.search-input {
  width: 260px;
  border-radius: 8px;
}

.status-select {
  width: 120px;
  border-radius: 8px;
}

.el-row {
  margin-top: 18px;
}

.club-card-col {
  margin-bottom: 28px;
}

.club-card {
  height: 100%;
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  transition: transform 0.3s, box-shadow 0.3s;
  background: #fff;
  border: 1.5px solid #e3e8ee;
  display: flex;
  flex-direction: column;
}
.club-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}

.club-image {
  width: 100%;
  height: 240px; /* 增加图片高度，使比例更协调 */
  object-fit: cover;
  border-radius: 16px 16px 0 0;
  transition: transform 0.3s ease; /* 添加过渡效果 */
  position: relative;
}

.club-card:hover .club-image {
  transform: scale(1.02); /* 添加悬停时的缩放效果 */
}

.club-info {
  padding: 24px 24px 16px 24px; /* 增加内边距 */
  flex: 1;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, rgba(255,255,255,0.95), #fff); /* 添加渐变背景 */
}

.club-card {
  padding: 18px 18px 10px 18px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.description {
  font-size: 14px;
  color: #666;
  margin: 10px 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.club-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.button-group {
  display: flex;
  gap: 10px;
}

.el-tag {
  border-radius: 6px;
  padding: 0 10px;
  height: 26px;
  line-height: 26px;
  font-size: 14px;
}

.el-button {
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s;
}
.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.12);
}
.el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}
.el-button--success {
  background: linear-gradient(90deg, #b7e4c7 0%, #d8f3dc 100%);
  border: none;
  color: #40916c;
}
.el-button--success:hover {
  background: linear-gradient(90deg, #d8f3dc 0%, #b7e4c7 100%);
  color: #52b788;
}
.pagination-container {
  margin-top: 28px;
  display: flex;
  justify-content: center;
}
::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}
.fab-create-club {
  position: fixed;
  top: 38%;
  right: 38px;
  width: 58px;
  height: 58px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 50%;
  box-shadow: 0 4px 18px rgba(100, 200, 180, 0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1002;
  transition: box-shadow 0.2s, transform 0.2s;
  border: 3px solid #fff;
}
.fab-create-club:hover {
  box-shadow: 0 8px 32px rgba(100, 200, 180, 0.28);
  transform: scale(1.08);
}
.plus-icon {
  font-size: 2.3rem;
  color: #fff;
  font-weight: bold;
  line-height: 1;
  user-select: none;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

/* 社团详情弹框样式 */
.club-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.club-detail-content {
  min-height: 500px;
}

.club-header {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.club-cover {
  width: 300px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
}

.club-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.club-name {
  font-size: 24px;
  font-weight: bold;
  color: #22577a;
  margin: 0;
}

.club-status {
  display: flex;
  gap: 8px;
}

.club-description {
  font-size: 16px;
  color: #666;
  margin: 12px 0;
  line-height: 1.6;
}

.club-stats {
  display: flex;
  gap: 24px;
  margin-top: auto;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #22577a;
  margin: 24px 0 16px;
}

.achievements, .rules {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  color: #666;
  line-height: 1.6;
  white-space: pre-line;
}

.ml-2 {
  margin-left: 8px;
}
</style>